package org.dashboard.client.widget.dailytopten;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Node;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import org.dashboard.shared.Props;

import java.util.Arrays;
import java.util.List;

/**
 */
public class DailyTopTenErrorWidget extends SimplePanel {

    interface Binder extends UiBinder<Widget, DailyTopTenErrorWidget> {
    }

    private static final Binder binder = GWT.create(Binder.class);

    public DailyTopTenErrorWidget(String width, String height, int refreshInterval) {
        super();

        setWidget(binder.createAndBindUi(this));

        final Node node = getElement().getChild(0);
        DOM.setStyleAttribute((Element) node, "width", width);
        DOM.setStyleAttribute((Element) node, "height", height);

        final DailyTopTenServiceAsync instance = (DailyTopTenServiceAsync) GWT.create(DailyTopTenService.class);
        String url = GWT.getModuleBaseURL() + "dailytopten";
        ((ServiceDefTarget) instance).setServiceEntryPoint(url);

        final AsyncCallback<List<List<String>>> statesAsyncCallback = new AsyncCallback<List<List<String>>>() {

            public void onFailure(Throwable caught) {
                Window.alert(caught.getMessage());
            }

            public void onSuccess(List<List<String>> lists) {
                Node rootNode = node.getChild(0).getChild(1);
                StringBuilder sb = new StringBuilder();
                sb.append("<marquee behavior=\"scroll\" direction=\"left\" style=\"font-size: 60px;font-weight: bold;\">");
                for(List<String> row:lists){
                   for(String text:row){
                      sb.append(text+"&nbsp;");
                   }
                    sb.append("&nbsp;&nbsp;&nbsp;###&nbsp;&nbsp;&nbsp;");
                }
                sb.append("</marquee>");

                ((Element) rootNode).setInnerHTML(sb.toString());
            }
        };

        final Timer timer = new Timer() {
            @Override
            public void run() {
                instance.getDailyTopTenError(statesAsyncCallback);
            }
        };
        timer.scheduleRepeating(refreshInterval);

        instance.getDailyTopTenError(statesAsyncCallback);
    }
}
